package com.tuling.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.util.DruidWebUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

//数据库连接池 创建连接池访问数据库的效率高
public class DruidUtils {
    //声明一个数据库连接池对象
    public static DruidDataSource dataSource;
    //静态代码块
    static {
        Properties properties = new Properties();
        InputStream is = DruidWebUtils.class.getResourceAsStream("/druid.properties");
        try {
            properties.load(is);
            //初始化数据源
            dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
        e.printStackTrace();
    }
    }



    //获取数据源
    public static DataSource getDataSource(){
        return dataSource;
    }

    //获取数据库链接
    public static Connection getConnection() {
        try {
            Connection connection = dataSource.getConnection();
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭相关资源
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs){
        try{
            if(rs!=null){
                rs.close();
            }
            if(stmt!=null){
                stmt.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

}
